#!/bin/sh
# PCP QA Test No. 1379
# Exercise Unix domain socket access to pmproxy and the PMWEBAPI(3)
#
# Copyright (c) 2019 Red Hat.
#

seq=`basename $0`
echo "QA output created by $seq"

# get standard environment, filters and checks
. ./common.product
. ./common.filter
. ./common.check

_check_series
_get_libpcp_config
$unix_domain_sockets || _notrun "No PCP unix domain socket support"
which curl >/dev/null 2>&1 || _notrun "No curl binary installed"
curl --help all | grep -q unix-socket || _notrun "No curl unix domain socket support"

_cleanup()
{
    cd $here
    if $need_restore
    then
	need_restore=false
	_restore_config $PCP_SYSCONF_DIR/labels
	_restore_config $PCP_SYSCONF_DIR/pmproxy/pmproxy.conf
	_restore_config $PCP_SYSCONF_DIR/pmproxy/pmproxy.options
	_sighup_pmcd
    fi
    if $pmproxy_was_running
    then
	echo "Restart pmproxy ..." >>$seq_full
	_service pmproxy restart >>$seq_full 2>&1
	_wait_for_pmproxy
    else
	echo "Stopping pmproxy ..." >>$seq_full
	_service pmproxy stop >>$seq_full 2>&1
    fi
    $sudo rm -rf $tmp $tmp.*
}

status=1	# failure is the default!
trap "_cleanup; exit \$status" 0 1 2 3 15

pmproxy_was_running=false
[ -f $PCP_RUN_DIR/pmproxy.pid ] && pmproxy_was_running=true
echo "pmproxy_was_running=$pmproxy_was_running" >>$seq_full

hostname=`hostname`
machineid=`_machine_id`
domainname=`_domain_name`

_filter_json()
{
    echo "== $@ ==" | tee -a $seq_full
    tee -a $seq_full > $tmp.unfiltered

    pmjson < $tmp.unfiltered > $tmp.filtered
    status=$?
    if [ $status -eq 0 ]; then
        cat $tmp.filtered | \
        sed \
            -e '/"machineid": .*/d' \
            -e 's,"series": .*,"series": "SERIES",g' \
            -e 's,"source": .*,"source": "SOURCE",g' \
            -e 's,"context": .*,"context": "CONTEXT",g' \
            -e 's,"hostname": .*,"hostname": "HOSTNAME",g' \
            -e 's,"hostspec": .*,"hostname": "HOSTNAME",g' \
            -e 's,"domainname": .*,"domainname": "DOMAINNAME",g' \
            -e 's,"timestamp": [0-9][0-9]*.[0-9][0-9]*,"timestamp": TIME,g' \
            -e 's,"msec": [0-9][0-9]*,"msec": MILLISECONDS,g' \
            -e 's,"usec": [0-9][0-9]*,"usec": MICROSECONDS,g' \
            -e 's,"nsec": [0-9][0-9]*,"nsec": NANOSECONDS,g' \
            -e 's,"sec": [0-9][0-9]*,"sec": SECONDS,g' \
        #end
        _get_context < $tmp.filtered > $tmp.context
    else
	echo "Invalid JSON: $status"
	cat $tmp.unfiltered
	rm -f $tmp.context
    fi
}

# Expecting 3 lines like ... the ^M's in the last line is a little tricky
#
#  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
#                                 Dload  Upload   Total   Spent    Left  Speed
#^M  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0^M100   249  100   249    0     0   243k      0 --:--:-- --:--:-- --:--:--  243k
_filter_curl()
{
    $PCP_AWK_PROG '
/% Total /		{ next }
/ Dload  Upload /	{ next }
/..:..:.. ..:..:../	{ next }
			{ print }'
}

_get_context()
{
    grep '"context"' | \
    sed \
        -e 's/.*context\": //g' \
        -e 's/,$//g' \
    #end
}

# real QA test starts here
_save_config $PCP_SYSCONF_DIR/labels
_save_config $PCP_SYSCONF_DIR/pmproxy/pmproxy.conf
_save_config $PCP_SYSCONF_DIR/pmproxy/pmproxy.options
need_restore=true

$sudo rm -rf $PCP_SYSCONF_DIR/labels/*
_sighup_pmcd || _exit 1

$sudo rm -f $PCP_SYSCONF_DIR/pmproxy/pmproxy.conf $PCP_SYSCONF_DIR/pmproxy/pmproxy.options
echo "--timeseries" >> $tmp.options
$sudo cp $tmp.options $PCP_SYSCONF_DIR/pmproxy/pmproxy.options
echo "[pmproxy]" >> $tmp.conf
echo "pcp.enabled = true" >> $tmp.conf
echo "http.enabled = true" >> $tmp.conf
echo "resp.enabled = true" >> $tmp.conf
echo "secure.enabled = true" >> $tmp.conf
$sudo cp $tmp.conf $PCP_SYSCONF_DIR/pmproxy/pmproxy.conf
cat $tmp.conf >> $seq_full

if ! _service pmproxy stop >/dev/null; then _exit 1; fi
if ! _service pmproxy start >>$seq_full 2>&1; then _exit 1; fi
_wait_for_pmproxy || _exit 1
cat $PCP_LOG_DIR/pmproxy/pmproxy.log >> $seq_full

socket="$PCP_RUN_DIR/pmproxy.socket"

# need sudo here to avoid "Permission denied" when trying to open
# $PCP_RUN_DIR/pmproxy.socket, e.g. on older Debian-based platforms
# also drop -s so we can see errors ... filter expected fluff out
# in _filter_curl
#
$sudo curl --unix-socket "$socket" \
	"http://localhost/pmapi/context" 2>$tmp.err \
| _filter_json "Check context creation on unix socket"
_filter_curl <$tmp.err

context="context=`cat $tmp.context`"
metrics='names=sample.long.one,sample.long.million'

$sudo curl --unix-socket "$socket" \
	"http://localhost/pmapi/fetch?$context&$metrics" 2>$tmp.err \
| _filter_json "Check metric fetching on that context"
_filter_curl <$tmp.err

# success, all done
status=0
exit
